package internal

import (
	"GameServer/Game/dbmodule"

	"github.com/globalsign/mgo/bson"
)

type AdUserLog struct {
	Uid    bson.ObjectId    `bson:"_id"`
	Name   string           `bson:"Name"`
	Advert map[string]int64 `bson:"advert"`
}

type AdCntLog struct {
	Id     int64            `bson:"_id"`
	Advert map[string]int64 `bson:"advert"`
}

type AdUser struct {
	Uid    string
	Name   string
	AdType int64
}

type Advert struct {
	adType chan int64
	adUser chan *AdUser
	ad     map[int64]string
}

func NewAdvert() *Advert {
	return &Advert{}
}

func (this *Advert) Init() {
	this.adType = make(chan int64, 1024)
	this.adUser = make(chan *AdUser, 1024)
	this.ad = make(map[int64]string)
	this.ad[1] = "AdGold"      // 金币广告
	this.ad[2] = "AdEnergy"    // 体力广告
	this.ad[3] = "AdTurntable" // 转盘广告
	this.ad[4] = "AdTV"        // 电视机广告
	this.ad[5] = "AdMagicBall" // 占卜广告
	this.ad[6] = "AdCard"      // 换卡广告
	this.ad[7] = "AdHideShop"  // 神秘商店广告
	this.ad[8] = "AdBattle"    // 战斗失败广告
	this.ad[9] = "AdAltar"     // 祭坛广告
}

func (this *Advert) Run(closeSig chan bool) {
	for {
		select {
		case <-closeSig:
			return
		case adUser := <-this.adUser:
			this.SaveAdUser(adUser)
		case adType := <-this.adType:
			this.SaveAdCnt(adType)
		}
	}
}

func (this *Advert) Destroy() {
	for item := range this.adUser {
		this.SaveAdUser(item)
	}
	for item := range this.adType {
		this.SaveAdCnt(item)
	}
}

func (this *Advert) AddAdUser(uid string, name string, adType int64) {
	this.adUser <- &AdUser{Uid: uid, Name: name, AdType: adType}
}

func (this *Advert) AddAdCnt(adType int64) {
	this.adType <- adType
}

func (this *Advert) SaveAdUser(adUser *AdUser) {
	obj := &AdUserLog{
		Uid:    bson.ObjectIdHex(adUser.Uid),
		Advert: make(map[string]int64),
	}
	dbmodule.MgoDB.GameLogDB.FindOne("AdUserLog", bson.M{"_id": obj.Uid}, nil, &obj)
	if obj.Advert == nil {
		obj.Advert = make(map[string]int64)
	}
	// 获取类型的名字
	adname := this.ad[adUser.AdType]
	// 统计该类型的广告点击次数
	obj.Advert[adname]++
	obj.Name = adUser.Name
	dbmodule.MgoDB.GameLogDB.Upsert("AdUserLog", bson.M{"_id": obj.Uid}, obj)
}

func (this *Advert) SaveAdCnt(adType int64) {
	obj := &AdCntLog{
		Id:     1,
		Advert: make(map[string]int64),
	}
	dbmodule.MgoDB.GameLogDB.FindOne("AdCntLog", bson.M{"_id": obj.Id}, nil, &obj)
	if obj.Advert == nil {
		obj.Advert = make(map[string]int64)
	}
	// 获取类型的名字
	adname := this.ad[adType]
	// 统计该类型的广告点击次数
	obj.Advert[adname]++
	dbmodule.MgoDB.GameLogDB.Upsert("AdCntLog", bson.M{"_id": obj.Id}, obj)
}
